package dao.dao;

import dao.bean.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoJdbcCachedConn implements UserDao {
    {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError(e);
        }
    }

    private Connection getConnection() throws SQLException {
//        return DriverManager.getConnection("jdbc:mysql://localhost:3306/production_eshop", "username", "password");
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/production_eshop", "root", "2479");
    }

    private Connection _conn;

    @Override
    public List<User> selectAll() throws SQLException {
        if (_conn == null) {
            _conn = getConnection();
        }

        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = _conn.prepareStatement("SELECT id, login FROM User");
            rs = ps.executeQuery();
            ArrayList<User> result = new ArrayList<User>();
            while (rs.next()) {
                int id = rs.getInt("id");
                String login = rs.getString("login");
                User user = new User(id);
                user.setLogin(login);
                result.add(user);
            }
            return result;
        } finally {
            JdbcUtils.closeQuietly(rs);
            JdbcUtils.closeQuietly(ps);
        }
    }

    @Override
    public int deleteById(int id) throws SQLException {
        Connection conn = getConnection();
        PreparedStatement ps = null;
        try {
            ps = conn.prepareStatement("DELETE FROM User WHERE id = ?");
            ps.setInt(1, id);
            return ps.executeUpdate();
        } finally {
            JdbcUtils.closeQuietly(ps);
            JdbcUtils.closeQuietly(conn);
        }
    }

    @Override
    public void insert(User user) throws SQLException {
        Connection conn = getConnection();
        PreparedStatement ps = null;
        try {
            ps = conn.prepareStatement("INSERT INTO User (login) VALUES (?)");
            ps.setString(1, user.getLogin());
            ps.executeUpdate();
        } finally {
            JdbcUtils.closeQuietly(ps);
            JdbcUtils.closeQuietly(conn);
        }
    }

    @Override
    public void shutdown() {
        JdbcUtils.closeQuietly(_conn);
    }
}
